<template>
  <div class="rehabilitation-services-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>康复服务管理</h3>
          <el-button type="primary" :icon="Plus" @click="openDialog('add')">新增服务</el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" label-width="90px" :inline="true">
          <el-form-item label="服务名称">
            <el-input v-model="searchForm.name" placeholder="输入服务名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="服务分类">
            <el-select v-model="searchForm.category" placeholder="选择分类" clearable style="width: 180px;">
              <el-option v-for="(cat, index) in categoryOptions" :key="index" :label="cat" :value="cat"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="价格区间">
            <el-input-number v-model="searchForm.minPrice" :min="0" :precision="2" placeholder="最低价" style="width: 130px;"></el-input-number>
            <span class="separator">-</span>
            <el-input-number v-model="searchForm.maxPrice" :min="0" :precision="2" placeholder="最高价" style="width: 130px;"></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
            <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="filteredServicesPaginated"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="id" label="服务编号" width="120"></el-table-column>
        <el-table-column prop="name" label="服务名称" min-width="180"></el-table-column>
        <el-table-column prop="category" label="分类" width="120"></el-table-column>
        <el-table-column label="价格(元)" width="120">
          <template #default="scope">
            <span>{{ scope.row.price.toFixed(2) }} / {{ scope.row.unitType }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="recommendedCourse" label="推荐疗程" min-width="150"></el-table-column>
        <el-table-column prop="department" label="科室" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button type="success" :icon="View" size="small" @click="viewServiceDetail(scope.row)">查看</el-button>
            <el-button type="primary" :icon="Edit" size="small" @click="openDialog('edit', scope.row)">编辑</el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredServices.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 康复服务表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增康复服务' : '编辑康复服务'"
      width="70%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="serviceFormRef"
        :model="serviceForm"
        :rules="serviceFormRules"
        label-width="120px"
      >
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="serviceForm.name" placeholder="请输入服务名称"></el-input>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务分类" prop="category">
              <el-select v-model="serviceForm.category" placeholder="请选择分类" style="width: 100%;">
                <el-option v-for="(cat, index) in categoryOptions" :key="index" :label="cat" :value="cat"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属科室" prop="department">
              <el-input v-model="serviceForm.department" placeholder="请输入所属科室"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务价格" prop="price">
              <el-input-number v-model="serviceForm.price" :min="0" :precision="2" style="width: 100%;"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计价单位" prop="unitType">
              <el-select v-model="serviceForm.unitType" placeholder="请选择计价单位" style="width: 100%;">
                <el-option label="单次" value="单次"></el-option>
                <el-option label="疗程" value="疗程"></el-option>
                <el-option label="小时" value="小时"></el-option>
                <el-option label="天" value="天"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="目标症状/适应症" prop="targetConditions">
          <el-select
            v-model="serviceForm.targetConditions"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入适应症/目标症状"
            style="width: 100%;"
          >
            <el-option
              v-for="item in conditionOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="推荐疗程" prop="recommendedCourse">
          <el-input v-model="serviceForm.recommendedCourse" placeholder="如：8-12周，每周3次"></el-input>
        </el-form-item>
        
        <el-form-item label="服务描述" prop="description">
          <el-input v-model="serviceForm.description" type="textarea" rows="3" placeholder="请输入服务描述"></el-input>
        </el-form-item>
        
        <el-form-item label="服务状态" prop="status">
          <el-select v-model="serviceForm.status" placeholder="请选择状态" style="width: 100%;">
            <el-option label="可预约" value="可预约"></el-option>
            <el-option label="暂停" value="暂停"></el-option>
            <el-option label="即将推出" value="即将推出"></el-option>
          </el-select>
        </el-form-item>
        
        <!-- 治疗内容 -->
        <el-divider content-position="left">治疗内容</el-divider>
        
        <div v-for="(item, index) in serviceForm.treatmentContent" :key="index" class="treatment-item">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item :label="`项目名称`" :prop="`treatmentContent[${index}].name`" :rules="{ required: true, message: '请输入项目名称', trigger: 'blur' }">
                <el-input v-model="item.name" placeholder="请输入项目名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item :label="`项目描述`" :prop="`treatmentContent[${index}].desc`" :rules="{ required: true, message: '请输入项目描述', trigger: 'blur' }">
                <el-input v-model="item.desc" placeholder="请输入项目描述"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2" class="delete-col">
              <el-button 
                type="danger" 
                :icon="Delete" 
                circle 
                @click="removeTreatmentItem(index)" 
                v-if="serviceForm.treatmentContent.length > 1">
              </el-button>
            </el-col>
          </el-row>
        </div>
        
        <div class="add-item">
          <el-button type="primary" plain :icon="Plus" @click="addTreatmentItem">添加治疗项目</el-button>
        </div>
        
        <!-- 治疗师 -->
        <el-form-item label="治疗师" prop="therapists">
          <el-select
            v-model="serviceForm.therapists"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入治疗师"
            style="width: 100%;"
          >
          </el-select>
        </el-form-item>
        
        <!-- 治疗设备 -->
        <el-form-item label="治疗设备" prop="equipment">
          <el-select
            v-model="serviceForm.equipment"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入治疗设备"
            style="width: 100%;"
          >
          </el-select>
        </el-form-item>
        
        <!-- 疗效评估方法 -->
        <el-form-item label="疗效评估方法" prop="efficacyEvaluation">
          <el-select
            v-model="serviceForm.efficacyEvaluation"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入疗效评估方法"
            style="width: 100%;"
          >
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 康复服务详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="康复服务详情"
      width="70%"
    >
      <div v-if="currentService" class="service-detail">
        <div class="detail-header">
          <h2>{{ currentService.name }}</h2>
          <el-tag :type="getStatusType(currentService.status)">{{ currentService.status }}</el-tag>
        </div>
        
        <div class="detail-info">
          <div class="info-item">
            <span class="label">服务编号：</span>
            <span>{{ currentService.id }}</span>
          </div>
          <div class="info-item">
            <span class="label">服务分类：</span>
            <span>{{ currentService.category }}</span>
          </div>
          <div class="info-item">
            <span class="label">服务价格：</span>
            <span class="price">¥{{ currentService.price.toFixed(2) }} / {{ currentService.unitType }}</span>
          </div>
          <div class="info-item">
            <span class="label">科室：</span>
            <span>{{ currentService.department }}</span>
          </div>
          <div class="info-item">
            <span class="label">推荐疗程：</span>
            <span>{{ currentService.recommendedCourse }}</span>
          </div>
        </div>
        
        <div class="detail-description">
          <h3>服务描述</h3>
          <p>{{ currentService.description }}</p>
        </div>
        
        <div class="detail-conditions">
          <h3>适应症/目标症状</h3>
          <div class="condition-tags">
            <el-tag 
              v-for="(condition, index) in currentService.targetConditions" 
              :key="index"
              class="condition-tag"
            >
              {{ condition }}
            </el-tag>
          </div>
        </div>
        
        <div class="detail-treatment">
          <h3>治疗内容</h3>
          <el-table :data="currentService.treatmentContent" border stripe style="width: 100%">
            <el-table-column prop="name" label="项目名称" width="200"></el-table-column>
            <el-table-column prop="desc" label="项目描述"></el-table-column>
          </el-table>
        </div>
        
        <div class="detail-resources">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="resource-section">
                <h3>治疗师</h3>
                <ul class="resource-list">
                  <li v-for="(therapist, index) in currentService.therapists" :key="index">
                    {{ therapist }}
                  </li>
                </ul>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="resource-section">
                <h3>治疗设备</h3>
                <ul class="resource-list">
                  <li v-for="(equipment, index) in currentService.equipment" :key="index">
                    {{ equipment }}
                  </li>
                </ul>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="resource-section">
                <h3>疗效评估方法</h3>
                <ul class="resource-list">
                  <li v-for="(evalMethod, index) in currentService.efficacyEvaluation" :key="index">
                    {{ evalMethod }}
                  </li>
                </ul>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { Search, Plus, Edit, Delete, Download, Refresh, View } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { rehabilitationServices } from '../../mock';

// 加载状态
const loading = ref(false);

// 康复服务数据
const servicesData = ref([]);

// 搜索条件
const searchForm = reactive({
  name: '',
  category: '',
  minPrice: null,
  maxPrice: null
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10
});

// 对话框状态
const dialogVisible = ref(false);
const dialogType = ref('add');
const detailDialogVisible = ref(false);
const currentService = ref(null);

// 表单引用
const serviceFormRef = ref(null);

// 表单数据
const serviceForm = reactive({
  id: '',
  name: '',
  category: '',
  targetConditions: [],
  price: 0,
  unitType: '单次',
  recommendedCourse: '',
  description: '',
  treatmentContent: [
    {
      name: '',
      desc: ''
    }
  ],
  therapists: [],
  equipment: [],
  efficacyEvaluation: [],
  status: '可预约',
  department: ''
});

// 表单验证规则
const serviceFormRules = {
  name: [
    { required: true, message: '请输入服务名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择服务分类', trigger: 'change' }
  ],
  targetConditions: [
    { required: true, message: '请至少添加一个目标症状/适应症', trigger: 'change' },
    { type: 'array', min: 1, message: '至少添加一个目标症状/适应症', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入服务价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于 0', trigger: 'blur' }
  ],
  unitType: [
    { required: true, message: '请选择计价单位', trigger: 'change' }
  ],
  recommendedCourse: [
    { required: true, message: '请输入推荐疗程', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入服务描述', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择服务状态', trigger: 'change' }
  ],
  department: [
    { required: true, message: '请输入所属科室', trigger: 'blur' }
  ]
};

// 分类选项
const categoryOptions = [
  '神经康复', '骨科康复', '儿童康复', '心脏康复', 
  '呼吸康复', '妇产康复', '老年康复', '言语康复'
];

// 适应症选项
const conditionOptions = [
  '脑卒中后遗症', '脊髓损伤', '帕金森病', '脑外伤后遗症',
  '骨折术后', '关节置换术后', '运动损伤', '颈肩腰痛',
  '心脏手术后', '心力衰竭', '慢性阻塞性肺疾病', '哮喘',
  '产后康复', '尿失禁', '吞咽障碍', '言语障碍',
  '发育迟缓', '自闭症', '脑瘫'
];

// 筛选后的服务数据
const filteredServices = computed(() => {
  let result = [...servicesData.value];
  
  if (searchForm.name) {
    result = result.filter(item => item.name.includes(searchForm.name));
  }
  
  if (searchForm.category) {
    result = result.filter(item => item.category === searchForm.category);
  }
  
  if (searchForm.minPrice !== null && searchForm.minPrice !== undefined) {
    result = result.filter(item => item.price >= searchForm.minPrice);
  }
  
  if (searchForm.maxPrice !== null && searchForm.maxPrice !== undefined) {
    result = result.filter(item => item.price <= searchForm.maxPrice);
  }
  
  return result;
});

// 获取当前页数据
const filteredServicesPaginated = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  return filteredServices.value.slice(start, end);
});

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case '可预约':
      return 'success';
    case '暂停':
      return 'danger';
    case '即将推出':
      return 'info';
    default:
      return 'warning';
  }
};

// 初始化数据
onMounted(() => {
  fetchData();
});

// 获取康复服务数据
const fetchData = () => {
  loading.value = true;
  try {
    // 这里使用mock数据，实际项目中应该是API请求
    servicesData.value = rehabilitationServices;
  } catch (error) {
    console.error('获取康复服务数据失败:', error);
    ElMessage.error('获取康复服务数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1;
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  searchForm.minPrice = null;
  searchForm.maxPrice = null;
  handleSearch();
};

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val;
};

const handleCurrentChange = (val) => {
  pagination.currentPage = val;
};

// 打开对话框
const openDialog = (type, row) => {
  dialogType.value = type;
  
  if (type === 'add') {
    resetForm();
  } else if (type === 'edit' && row) {
    // 深拷贝数据，避免直接修改原数据
    Object.keys(serviceForm).forEach(key => {
      if (Array.isArray(row[key])) {
        serviceForm[key] = JSON.parse(JSON.stringify(row[key] || []));
      } else {
        serviceForm[key] = row[key];
      }
    });
  }
  
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  serviceForm.id = 'RS-' + Date.now().toString().substr(-6);
  serviceForm.name = '';
  serviceForm.category = '';
  serviceForm.targetConditions = [];
  serviceForm.price = 0;
  serviceForm.unitType = '单次';
  serviceForm.recommendedCourse = '';
  serviceForm.description = '';
  serviceForm.treatmentContent = [
    {
      name: '',
      desc: ''
    }
  ];
  serviceForm.therapists = [];
  serviceForm.equipment = [];
  serviceForm.efficacyEvaluation = [];
  serviceForm.status = '可预约';
  serviceForm.department = '';
  
  if (serviceFormRef.value) {
    serviceFormRef.value.resetFields();
  }
};

// 添加治疗项目
const addTreatmentItem = () => {
  serviceForm.treatmentContent.push({
    name: '',
    desc: ''
  });
};

// 移除治疗项目
const removeTreatmentItem = (index) => {
  serviceForm.treatmentContent.splice(index, 1);
};

// 提交表单
const submitForm = () => {
  serviceFormRef.value.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 添加新服务
        servicesData.value.unshift({...serviceForm});
        ElMessage.success('新增康复服务成功');
      } else {
        // 更新服务
        const index = servicesData.value.findIndex(item => item.id === serviceForm.id);
        if (index !== -1) {
          servicesData.value[index] = {...serviceForm};
          ElMessage.success('更新康复服务成功');
        }
      }
      dialogVisible.value = false;
    } else {
      return false;
    }
  });
};

// 删除服务
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除康复服务"${row.name}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = servicesData.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      servicesData.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 查看服务详情
const viewServiceDetail = (row) => {
  currentService.value = row;
  detailDialogVisible.value = true;
};
</script>

<style scoped>
.rehabilitation-services-container {
  padding: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
}

.search-area {
  margin-bottom: 20px;
}

.separator {
  margin: 0 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.treatment-item {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f9fafc;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.delete-col {
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-item {
  margin-bottom: 20px;
}

.service-detail {
  padding: 0 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.detail-header h2 {
  margin: 0;
  font-size: 22px;
}

.detail-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
}

.label {
  font-weight: bold;
  min-width: 100px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.detail-description, .detail-conditions, .detail-treatment, .detail-resources {
  margin-bottom: 24px;
}

.detail-description h3, .detail-conditions h3, .detail-treatment h3, .resource-section h3 {
  font-size: 18px;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.condition-tags {
  display: flex;
  flex-wrap: wrap;
}

.condition-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.resource-section {
  height: 100%;
  background-color: #f9fafc;
  border-radius: 4px;
  padding: 16px;
}

.resource-list {
  margin: 0;
  padding-left: 20px;
}

.resource-list li {
  margin-bottom: 8px;
}
</style> 